/*
*  This file is part of mangusta
*
*  mangusta is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  mangusta is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  You should have received a copy of the GNU General Public License
*  along with mangusta; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  US
*
*  Author: <antonino.calderone@ericsson.com>, <acaldmail@gmail.com>
*
*/


/* -------------------------------------------------------------------------- */

#include "nu_rt_prog_ctx.h"
#include "nu_stmt_if.h"
#include "nu_lang_defs.h"


/* -------------------------------------------------------------------------- */

namespace nu
{


/* -------------------------------------------------------------------------- */

stmt_if_t::stmt_if_t(
   prog_ctx_t & ctx,
   expr_any_t::handle_t condition)
   :
   stmt_t(ctx),
   _condition(condition)
{
   ctx.if_metadata.data[ctx.compiletime_pc].pc_if_stmt = ctx.compiletime_pc;
   ctx.if_metadata.pc_stack.push(ctx.compiletime_pc);
   ctx.parsing_scope.push(PROGLANG_STMT_IF);
}


/* -------------------------------------------------------------------------- */

stmt_if_t::stmt_cl_t stmt_if_t::get_cl() const throw()
{
   return stmt_cl_t::IF_BLOCK_BEGIN;
}


/* -------------------------------------------------------------------------- */

void stmt_if_t::run(rt_prog_ctx_t& ctx)
{
   auto & ifctxs = ctx.if_metadata;
   auto & metadata_it = ctx.if_metadata.data.find(ctx.runtime_pc);

   rt_error_code_t::get_instance().throw_if(
      metadata_it == ctx.if_metadata.data.end(),
      ctx.runtime_pc.get_line(),
      rt_error_code_t::E_INTERNAL,
      PROGLANG_STMT_IF);

   if (static_cast<bool>(_condition->eval(ctx)) == false)
   {
      metadata_it->second.condition = false;

      if (metadata_it->second.else_list.empty())
      {
         ctx.go_to(metadata_it->second.pc_endif_stmt);
      }

      else
      {
         ctx.go_to(*metadata_it->second.else_list.begin());
      }
   }

   else
   {
      metadata_it->second.condition = true;

      ctx.go_to_next();
   }
}



/* -------------------------------------------------------------------------- */


} // namespace nu


/* -------------------------------------------------------------------------- */

